import Avatar from "@/components/avatar"
import http from "@/request"
import user from "@/store/user"
import viewMode from "@/store/viewMode"
import { ShowLoading, ShowToast } from "@/utils"
import { View, Text, Image, Button, Input } from "@tarojs/components"
import Taro from "@tarojs/taro"
import React, { useEffect, useState } from "react"
import { AtModal, AtModalHeader, AtModalContent, AtModalAction } from "taro-ui"
import { observer } from "mobx-react"
import { MoneyFormat } from "@/utils/format"
import account from "@/store/account"
import moment from "moment"
import PageNav from "@/components/pageNav"
import AccountSelecter from "@/components/accountSelecter"
import "./index.scss"

let inited = false
const UserCard: React.FC = observer(() => {
    const [editVisible, setEditVisible] = useState(false)
    const [showSelecter, setShowSelecter] = useState(false)
    const [userName, setUserName] = useState('')
    const [billNum, setBillNum] = useState(0)
    const [balance, setBalance] = useState(0)

    const avatarChange = (avatarUrl) => {
        updateUserInfo({
            ...user.info,
            avatarUrl
        })
    }

    const saveUserName = () => {
        updateUserInfo({
            ...user.info,
            userName
        })
    }

    const updateUserInfo = (info) => {
        ShowLoading()
        http.post('/user/edit', info).then(_ => {
            user.updateInfo(info)
            ShowToast('保存成功')
            setEditVisible(false)
        }).catch(err => {
            ShowToast(err.msg || '数据保存失败！')
        })
    }

    const getDayNum = (val) => {
        return Math.ceil((new Date().getTime() - new Date(val).getTime()) / (24 * 3600 * 1000))
    }

    const queryCount = () => {
        return http.get(`/bills/count?accountId=${account.activeAccount?.id}`).then(res => {
            setBillNum(res.data)
        })
    }
    const toPage = (url: string) => {
        Taro.navigateTo({
            url
        })
    }
    const querySummary = () => {
        return http.post('/bills/statistics/summary', {
            accountId: account.activeAccount?.id,
            endDate: moment().format('YYYY-MM-DD'),
            startDate: "2024-01-01"
        }).then((res) => {
            const balance = res.data.balance + (account.activeAccount?.members || []).reduce((sum, cur) => {
                return sum + (cur.initAmount || 0)
            }, 0)
            setBalance(balance)
        })
    }

    const init = async () => {
        await queryCount()
        await querySummary()
        inited = true
    }

    Taro.useDidShow(() => {
        init()
    })

    useEffect(() => {
        inited && init()
    }, [account.accountIndex])

    useEffect(() => {
        if (inited) {
            viewMode.setBehind(editVisible)
        }
    }, [editVisible])

    Taro.useDidHide(() => {
        setEditVisible(false)
    })

    return (
        <View className="user-card">
            <View className="page-header flex-column flex-center need-filter">
                <PageNav className="mine-page-header flex-row">
                    <View onClick={() => setShowSelecter(true)} className="account-name font-size24 text-main-color">
                        <View className="bg page-background"></View>
                        <Text>{account.activeAccount?.name}</Text>
                        <Text className="iconfont icon-base-down"></Text>
                    </View>
                    <View className="flex1"></View>
                </PageNav>
                <View className="bg-container page-background">
                    <Image className="bg-img" mode="aspectFill" src="https://study-plans-file.oss-cn-chengdu.aliyuncs.com/design/banner.jpg"></Image>
                </View>
                <View className="text-main-color flex-row flex-item">
                    <Avatar
                        editMode
                        showDetail
                        url={user.info?.avatarUrl}
                        onChange={avatarChange}
                        className="flex-column flex-item" />
                    <View className="user-name font-size32 flex-row flex-item" onClick={() => {
                        setUserName(user.info?.userName || '')
                        setEditVisible(true)
                    }}>
                        <Text>{user.info?.userName || '点击此处编辑名字'}</Text>
                        <Text className="font-size36 iconfont icon-bianji"></Text>
                    </View>
                </View>
                <View className="flex1 flex-row counting-info font-size24">
                    <View className="flex1 flex-center">
                        <View className="label">累计：</View>
                        <View className="count-value">
                            {/* <Text>{billNum}</Text>笔/<Text>{getDayNum(user.info?.createTime)}</Text>天 */}
                            <Text>{billNum}</Text>笔/<Text>{getDayNum(account.activeAccount?.createTime)}</Text>天
                        </View>
                    </View>
                    <View className="line"></View>
                    <View className="flex1 flex-center">
                        <View className="label">结余：</View>
                        <View className="balance-value font-size36" onClick={() => toPage('/pages/balance/index')}>{MoneyFormat(balance)}<Text className="iconfont icon-bianji"></Text></View>
                    </View>
                </View>
            </View>
            <AtModal isOpened={editVisible} className="edit-modal" onClose={() => setEditVisible(false)}>
                <AtModalHeader>编辑名称</AtModalHeader>
                <AtModalContent>
                    <Input className="target-val-input" value={userName} onInput={(e) => {
                        const target = e.target as HTMLInputElement
                        setUserName(target.value)
                    }}></Input>
                </AtModalContent>
                <AtModalAction>
                    <Button onClick={() => setEditVisible(false)}>取消</Button>
                    <Button onClick={saveUserName}>确定</Button>
                </AtModalAction>
            </AtModal>
            <AccountSelecter show={showSelecter} onClose={() => setShowSelecter(false)}></AccountSelecter>
        </View>
    )
})

export default UserCard